//
//  KFDInvestmentCommunityPostView.m
//  KFD
//
//  Created by JIRENTIANXIANG on 7/5/15.
//  Copyright © 2015 kfd. All rights reserved.
//

#import "KFDInvestmentCommunityViewCell.h"
#import "JRTXLinearLayout.h"
#import "ui_config.h"
#import "KFDInvestmentCommunityPost.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "NSDate+format.h"
#import "KFDICLikesView.h"
#import "KFDStringConcatenator.h"
#import "KFDInvestmentCommunityManager.h"
#import "JTToast.h"
#import "KFDAccountManager.h"
#import "UIAlertController+KFD.h"
#import "KFDEmoticonParser.h"
#import "TQRichTextView.h"

@interface KFDInvestmentCommunityViewCell ()

@property (weak,nonatomic) UIWindow* window;
@property (strong,nonatomic) UIView* background;
@property (strong,nonatomic) UIImageView* bigPic;

@property (strong,nonatomic) UIImageView* avatar;
@property (strong,nonatomic) UILabel* nicknameLabel;
@property (strong,nonatomic) TQRichTextView* contentTextView;

@property (strong,nonatomic) NSMutableArray* pictures;
@property (strong,nonatomic) KFDTimePraiseReplyContainer* tprContainer;
@property (strong,nonatomic) KFDICLikesView* likesView;
@property (strong,nonatomic) NSMutableArray* commentLabels;

@end

@implementation KFDInvestmentCommunityViewCell

-(void)setup
{
    [self setupNicknameLabel];
    [self setupTPRContainer];
    [self setupAvatar];
    self.window=[UIApplication sharedApplication].windows.firstObject;
}

-(void)setPost:(KFDInvestmentCommunityPost *)post
{
    _post=post;
    
    self.nicknameLabel.text=post.nickname;
    [self.tprContainer.praiseButton setImage:[UIImage imageNamed:self.post.islike?@"praise-green-ico":@"praise-ico"] forState:UIControlStateNormal];
    
    if (!post.content || post.content.length == 0) {
        post.content = @"(无内容)";
    }
    
    CGRect rect = [TQRichTextView boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-70, MAXFLOAT) font:[UIFont systemFontOfSize:13] string:post.content lineSpace:1.0f];
    self.contentTextView = [[TQRichTextView alloc] initWithFrame:CGRectMake(0, 20, rect.size.width, rect.size.height)];
    self.contentTextView.text = post.content;
    self.contentTextView.lineSpace = 1.0f;
    self.contentTextView.font = [UIFont systemFontOfSize:13.0f];
    self.contentTextView.backgroundColor=KFD_WHITE;
    
    self.tprContainer.timeLabel.text=post.date.postFormat;
    [self.tprContainer.praiseButton setTitle:[NSString stringWithFormat:@"赞%ld",(long)post.likes] forState:UIControlStateNormal];
    
    if (post.piclist&&post.piclist.count>0) {
        self.pictures=[[NSMutableArray alloc] init];
        for (int i=0;i<post.piclist.count;i++) {
            UIImageView* picture=[[UIImageView alloc] initWithFrame:CGRectMake(i*50, 0, 46, 55)];
            [picture sd_setImageWithURL:post.piclist[i][@"thumb"]];
            [self.pictures addObject:picture];
            UITapGestureRecognizer* tapRecognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(thumbnailTapped:)];
            picture.userInteractionEnabled=YES;
            [picture addGestureRecognizer:tapRecognizer];
        }
    }
    if (post.newlikes&&post.newlikes.count>0) {
        self.likesView=[[NSBundle mainBundle] loadNibNamed:@"KFDICLikesView" owner:nil options:nil].firstObject;
        self.likesView.frame=CGRectMake(0, 0, SCREEN_WIDTH-55, 27);
        NSMutableArray* nicknameArr=[NSMutableArray array];
        for (NSDictionary* like in post.newlikes) {
            NSString* nickname=like[@"nickname"];
            if (nickname) {
                [nicknameArr addObject:like[@"nickname"]];
            }
        }
        KFDStringConcatenator* concatenator=[KFDStringConcatenator concatenatorWithSeparator:@"、"];
        NSString* likesText=[concatenator concatenateStringsInArray:nicknameArr];
        NSMutableString* tailText=[[NSMutableString alloc] init];
        if (self.post.likes>5) {
            [tailText appendString:@"等"];
        }
        [tailText appendString:@"觉得很赞"];
        
        self.likesView.likesLabel.text=likesText;
        self.likesView.tail.text=tailText;
    }
    if (post.newcomments&&post.newcomments.count>0) {
        self.commentLabels=[[NSMutableArray alloc] init];
        for (KFDICPostComment* comment in post.newcomments) {
            NSString* names=[comment.uid isEqualToString:comment.cuid]?comment.nickname:[NSString stringWithFormat:@"%@回复%@",comment.nickname,comment.cnickname];
            NSMutableAttributedString* attributedComment=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ : %@",names,comment.content] attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11]}];
            
            NSMutableString* str=attributedComment.string.mutableCopy;
            [attributedComment addAttribute:NSForegroundColorAttributeName value:KFD_NICKNAME_COLOR range:[str rangeOfString:comment.nickname]];
            NSMutableString* placeholder=[NSMutableString string];
            for (int i=0; i<comment.nickname.length; i++) {
                [placeholder appendString:@"`"];
            }
            [str replaceCharactersInRange:[str rangeOfString:comment.nickname] withString:placeholder];
            [attributedComment addAttribute:NSForegroundColorAttributeName value:KFD_NICKNAME_COLOR range:[str rangeOfString:comment.cnickname]];
            
//            UILabel* label=[[UILabel alloc] init];
//            label.attributedText=attributedComment;
//            [self.commentLabels addObject:label];
            
            NSString* commentStr=[NSString stringWithFormat:@"%@ : %@",names,comment.content];
            CGRect rect = [TQRichTextView boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-55, MAXFLOAT) font:[UIFont systemFontOfSize:11] string:commentStr lineSpace:1.0f];
            TQRichTextView* commentView = [[TQRichTextView alloc] initWithFrame:CGRectMake(0, 20, rect.size.width, rect.size.height)];
            commentView.text = commentStr;
            commentView.lineSpace = 1.0f;
            commentView.font = [UIFont systemFontOfSize:11];
            commentView.backgroundColor=KFD_WHITE;
            commentView.nickname0=comment.nickname;
            if ([comment.uid isEqualToString:comment.cuid]) {
//                commentView.nickname1Length=0;
            }else{
//                commentView.nickname1Length=comment.cnickname.length;
                commentView.nickname1=comment.cnickname;
            }
            commentView.nicknameColor=KFD_NICKNAME_COLOR;
            [self.commentLabels addObject:commentView];
        }
    }
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:post.face] placeholderImage:[UIImage imageNamed:@"avatar"]];
}

-(void)thumbnailTapped:(UIGestureRecognizer*)recognizer
{
    UIImageView* thumbnail=(UIImageView*)recognizer.view;
    UIImage* image=thumbnail.image;
    self.bigPic=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    
    self.bigPic.contentMode=UIViewContentModeScaleAspectFit;
    self.bigPic.image=image;
    
    self.background=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.background.backgroundColor=[UIColor blackColor];
    self.background.alpha=0.8;
    self.background.userInteractionEnabled=YES;
    UITapGestureRecognizer* tapRecognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bigPicTapped:)];
    [self.background addGestureRecognizer:tapRecognizer];
    [self.window addSubview:self.background];
    [self.window addSubview:self.bigPic];
    self.background.alpha=0;
    self.bigPic.alpha=0;
    [UIView animateWithDuration:0.4 animations:^{
        self.background.alpha=0.8;
        self.bigPic.alpha=1;
    }];
}

-(void)bigPicTapped:(UIGestureRecognizer*)recognizer
{
    [UIView animateWithDuration:0.4 animations:^{
        self.background.alpha=0;
        self.bigPic.alpha=0;
    } completion:^(BOOL finished) {
        if (self.bigPic) {
            [self.bigPic removeFromSuperview];
            self.bigPic=nil;
        }
        if (self.background) {
            [self.background removeFromSuperview];
            self.background=nil;
        }
    }];
}

-(void)setupAvatar
{
    self.avatar=[[UIImageView alloc] initWithFrame:CGRectMake(11, 11, 32, 32)];
    self.avatar.layer.cornerRadius=self.avatar.bounds.size.width/2;
    self.avatar.layer.masksToBounds=YES;
}

-(void)setupNicknameLabel
{
    self.nicknameLabel=[[UILabel alloc] init];
    self.nicknameLabel.textColor=KFD_BLUE;
    self.nicknameLabel.font=[UIFont systemFontOfSize:11];
}

-(void)setupTPRContainer
{
    self.tprContainer=[[NSBundle mainBundle] loadNibNamed:@"KFDTimePraiseReplyContainer" owner:nil options:nil].firstObject;
    self.tprContainer.frame=CGRectMake(0, 0, SCREEN_WIDTH-55, 31);
    [self.tprContainer.praiseButton addTarget:self action:@selector(praiseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.tprContainer.praiseButton addTarget:self action:@selector(praiseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.tprContainer.commentButton addTarget:self action:@selector(commentButtonPresssed) forControlEvents:UIControlEventTouchUpInside];
}

-(void)praiseButtonPressed:(UIButton*)sender
{
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    if (accountManager.isLogin) {
        self.post.islike=!self.post.islike;
        KFDInvestmentCommunityManager* manager=[[KFDInvestmentCommunityManager alloc] init];
        if (!self.post.islike) {
            [manager cancelPraisePost:self.post.id successHandler:^(NSInteger numberOfLikes) {
                [[NSNotificationCenter defaultCenter] postNotificationName:KFDICRepraisedNotification object:nil];
            } failureHandler:^(KFDResponseBody *response) {
                [[JTToast makeText:response.message] showInView:self size:CGSizeMake(response.message.length*20, 40)];
            }];
        }else{
            [manager praisePost:self.post.id successHandler:^(NSInteger numberOfLikes) {
                [[NSNotificationCenter defaultCenter] postNotificationName:KFDICRepraisedNotification object:nil];
            } failureHandler:^(KFDResponseBody *response) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[JTToast makeText:response.message] showInView:self size:CGSizeMake(response.message.length*20, 40)];
                });
            }];
        }
    }else{
        [UIAlertController presentLoginRegisterAlertControllerWithMessage:@"请您先登录或注册" byViewController:self.viewController];
    }
}

-(void)commentButtonPresssed
{
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    if (accountManager.isLogin) {
        if (self.commentAction) {
            self.commentAction();
        }
    }else{
        [UIAlertController presentLoginRegisterAlertControllerWithMessage:@"请您先登录或注册" byViewController:self.viewController];
    }
}

-(CGFloat)layout
{
    JRTXLinearLayout* layout=[[JRTXLinearLayout alloc] initWithFrame:CGRectMake(55, 0, SCREEN_WIDTH-55, 0)];
    [layout appendBlankLineWithHeight:11];
    [layout appendLabel:self.nicknameLabel widthLimit:SCREEN_WIDTH-55-20 alignment:JRTXLinearLayoutAlignmentLeft];
    [layout appendBlankLineWithHeight:11];
    [layout appendView:self.contentTextView alignment:JRTXLinearLayoutAlignmentLeft];
    if (self.pictures) {
        [layout appendBlankLineWithHeight:10];
        UIView* pictureContainer=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-55, 55)];
        for (UIImageView* picture in self.pictures) {
            [pictureContainer addSubview:picture];
        }
        [layout appendView:pictureContainer alignment:JRTXLinearLayoutAlignmentLeft];
    }
    [layout appendView:self.tprContainer alignment:JRTXLinearLayoutAlignmentLeft];
    [layout appendView:self.likesView alignment:JRTXLinearLayoutAlignmentLeft];
    [layout appendBlankLineWithHeight:5];
//    for (UILabel* label in self.commentLabels) {
//        [layout appendLabel:label widthLimit:SCREEN_WIDTH-55-20 alignment:JRTXLinearLayoutAlignmentLeft];
//        [layout appendBlankLineWithHeight:10];
//    }
    for (TQRichTextView* commentView in self.commentLabels) {
        [layout appendView:commentView alignment:JRTXLinearLayoutAlignmentLeft];
        [layout appendBlankLineWithHeight:10];
    }
    [self addSubview:layout.view];
    [self addSubview:self.avatar];
    return layout.view.frame.size.height;
}

@end
